package cn.darkhorse.device.service.impl;

import cn.darkhorse.common.constant.CommonConstant;
import cn.darkhorse.device.mapper.MesRepairCommissionInfoMapper;
import cn.darkhorse.device.pojo.MesRepairCommissionInfo;
import cn.darkhorse.device.service.MesRepairCommissionInfoService;
import cn.darkhorse.device.vo.MesRepairCommissionInfoVO;
import cn.darkhorse.messystem.pojo.SaasTeam;
import cn.darkhorse.messystem.service.SaasTeamService;
import cn.darkhorse.messystem.vo.SysUserVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 维修单 服务实现类
 * </p>
 *
 * @author yangtianqi
 * @since 2024-05-29
 */
@Service
public class MesRepairCommissionInfoServiceImpl extends ServiceImpl<MesRepairCommissionInfoMapper, MesRepairCommissionInfo> implements MesRepairCommissionInfoService {


    @Autowired
    private ISysUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SaasTeamService teamService;
//
//    @Value("${spring.datasource.druid.master.dbname}")
//    public  String MAIN_DB_NAME ;
//    @Value("${spring.datasource.druid.master.url}")
//    private String url;
//    @Value("${spring.datasource.druid.master.username}")
//    private String username;
//    @Value("${spring.datasource.druid.master.password}")
//    private String password;
    /**
     * 获取维修单信息
     * @param mesRepairCommissionInfo
     * @return
     */
    @Override
    public List<MesRepairCommissionInfo> listAll(MesRepairCommissionInfo mesRepairCommissionInfo) {

        LambdaQueryWrapper<MesRepairCommissionInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.orderByDesc(MesRepairCommissionInfo::getGmtCreate);
        if (mesRepairCommissionInfo != null) {
            // 设备编码
            if (mesRepairCommissionInfo.getDeviceCode() != null && !mesRepairCommissionInfo.getDeviceCode().isEmpty()){
                lambdaQueryWrapper.like(MesRepairCommissionInfo::getDeviceCode,mesRepairCommissionInfo.getDeviceCode());
            }
            // 设备名称
            if (mesRepairCommissionInfo.getDeviceName() != null && !mesRepairCommissionInfo.getDeviceName().isEmpty()){
                lambdaQueryWrapper.like(MesRepairCommissionInfo::getDeviceName,mesRepairCommissionInfo.getDeviceName());
            }
            // 外委单位
            if (mesRepairCommissionInfo.getOrganizationName() != null && !mesRepairCommissionInfo.getOrganizationName().isEmpty()){
                lambdaQueryWrapper.like(MesRepairCommissionInfo::getOrganizationName,mesRepairCommissionInfo.getOrganizationName());
            }
            // 处理状态
            if (mesRepairCommissionInfo.getDisposeStatus() != null){
                lambdaQueryWrapper.eq(MesRepairCommissionInfo::getDisposeStatus,mesRepairCommissionInfo.getDisposeStatus());
            }
            // 维修负责人
            if (mesRepairCommissionInfo.getRepairPrincipal() != null && !mesRepairCommissionInfo.getRepairPrincipal().isEmpty()){
                lambdaQueryWrapper.apply("(SELECT count(0) from sys_user where nick_name like '%"+mesRepairCommissionInfo.getRepairPrincipal()+"%' and FIND_IN_SET(sys_user.user_id, mes_repair_commission_info.repair_principal))>0");

            }
            // 设备类型
            if (mesRepairCommissionInfo.getDeviceType() != null){
                lambdaQueryWrapper.like(MesRepairCommissionInfo::getDeviceType,mesRepairCommissionInfo.getDeviceType());
            }

        }

        // 负责人 姓名翻译
        List<MesRepairCommissionInfo> repairCommissionInfos = list(lambdaQueryWrapper);
        for (MesRepairCommissionInfo commissionInfo : repairCommissionInfos) {

            String principal = commissionInfo.getRepairPrincipal();
            Set<String> set = new HashSet<>();
            if (StringUtils.isNotEmpty(principal)) {
                String[] ids = principal.split(",");
                for (String id : ids) {
                    if (id != null){
                        try {
                            Long l = Long.valueOf(id);
                            SysUser sysUser = userService.selectUserById(l);
                            if (sysUser != null){
                                set.add(sysUser.getNickName());
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                }
                commissionInfo.setRepairPrincipal(String.join(",", set));
            }
        }
        return repairCommissionInfos;
    }


    /**
     * 保存维修单信息
     * @param mesRepairCommissionInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveRepairCommissionInfo(MesRepairCommissionInfoVO mesRepairCommissionInfo) {
        if (mesRepairCommissionInfo.getId() == null){

            mesRepairCommissionInfo.setDisposeStatus(0);
            if (StringUtils.isEmpty(mesRepairCommissionInfo.getOrderNum())){

                //生成单号
//                SaasUserVO companyByName = saasUserService.getCompanyByName(SecurityUtils.getUsername());


                try {
                    Class.forName("com.mysql.cj.jdbc.Driver");

                    LocalDateTime now = LocalDateTime.now();
                    String currentDate = now.format(DateTimeFormatter.ofPattern("yyyyMMdd")); // 格式化

                    //Redis key的前缀
                    String key;
//                    if (companyByName!=null){
                        key = "commission:order:code:"+":"+currentDate;
//                    }
                    //查询 key 是否存在， 不存在返回 1 ，存在的话则自增加1
                    Long autoID = stringRedisTemplate.opsForValue().increment(key, 1);
                    if(1L == autoID){
                        stringRedisTemplate.expire(key, 86400, TimeUnit.SECONDS);
                    }
                    String value = StringUtils.leftPad(String.valueOf(autoID), 4, "0");
                    String code = MessageFormat.format("{0}{1}{2}", CommonConstant.COMMISSION_INFO_ORDER_NUMBER_PREFIX, currentDate,value);
                    mesRepairCommissionInfo.setOrderNum(code);
                }catch (Exception e) {
                    throw new RuntimeException(e);
                }


            }
        }
        List<SysUserVO> list = mesRepairCommissionInfo.getRepairPrincipalList();
        if (list!=null && !list.isEmpty()){
            List<Long> longs = list.stream().map(SysUser::getUserId).collect(Collectors.toList());
            mesRepairCommissionInfo.setRepairPrincipal(StringUtils.join(longs,","));
        }

        return saveOrUpdate(mesRepairCommissionInfo);
    }


    /**
     * 批量删除维修单信息
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDelete(Long[] ids) {
        return removeByIds(Arrays.asList(ids));
    }


    /**
     * 查看维修单信息
     * @param id
     * @return
     */
    @Override
    public MesRepairCommissionInfo view(Long id) {
        MesRepairCommissionInfo info = getById(id);
        MesRepairCommissionInfoVO commissionInfoVO = new MesRepairCommissionInfoVO();
        BeanUtils.copyProperties(info,commissionInfoVO);

        String repairPrincipal = info.getRepairPrincipal();

        // 负责人
        if (StringUtils.isNotEmpty(repairPrincipal)) {
            List<Long> longList = Arrays.stream(repairPrincipal.split(",")).map(Long::valueOf).collect(Collectors.toList());
            List<SysUserVO> usersByUserId = teamService.getUsersByUserId(longList);
            for (SysUserVO sysUserVO : usersByUserId) {
                // 班组
                String teamName = sysUserVO.getTeams().stream().map(SaasTeam::getName).collect(Collectors.joining(","));
                sysUserVO.setTeamName(teamName);
//                sysUserVO.setDeptString(sysUserVO.getDept().getDeptName());
//                sysUserVO.setDeptName(sysUserVO.getDept().getDeptName());
            }
            commissionInfoVO.setRepairPrincipalList(usersByUserId);
        }
        return commissionInfoVO;
    }


    /**
     * app专用列表接口
     * @param mesRepairCommissionInfo
     * @return
     */
    @Override
    public List<MesRepairCommissionInfo> listAllApp(MesRepairCommissionInfo mesRepairCommissionInfo) {
        // 负责人 姓名翻译
        Long userId = SecurityUtils.getUserId();
        List<MesRepairCommissionInfo> repairCommissionInfos =
                lambdaQuery().eq(MesRepairCommissionInfo::getDisposeStatus,0)
                        .apply("FIND_IN_SET("+userId+",mes_repair_commission_info.repair_principal)")
                        .orderByDesc(MesRepairCommissionInfo::getGmtCreate)
                        .list();
        for (MesRepairCommissionInfo commissionInfo : repairCommissionInfos) {

            String principal = commissionInfo.getRepairPrincipal();
            Set<String> set = new HashSet<>();
            if (StringUtils.isNotEmpty(principal)) {
                String[] ids = principal.split(",");
                for (String id : ids) {
                    if (id != null){
                        set.add(userService.selectUserById(Long.valueOf(id)).getNickName());
                    }

                }
                commissionInfo.setRepairPrincipal(String.join(",", set));
            }
        }
        return repairCommissionInfos;
    }

    @Override
    public String getApplyCode() {
        //Redis key的前缀
        String key;
        String currentDate;

        try {

            LocalDateTime now = LocalDateTime.now();
            currentDate = now.format(DateTimeFormatter.ofPattern("yyyyMMdd")); // 格式化
//                    if (companyByName!=null){
            key = "commission:order:code:"+":"+currentDate;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        //查询 key 是否存在， 不存在返回 1 ，存在的话则自增加1
        Long autoID = stringRedisTemplate.opsForValue().increment(key, 1);
        if(1L == autoID){
            stringRedisTemplate.expire(key, 86400, TimeUnit.SECONDS);
        }
        String value = StringUtils.leftPad(String.valueOf(autoID), 4, "0");
        String code = MessageFormat.format("{0}{1}{2}", CommonConstant.COMMISSION_INFO_ORDER_NUMBER_PREFIX, currentDate,value);
        return code;
    }
}
